package com.example.service.impl;

import com.example.domain.menu.MenuTree;
import com.example.domain.po.LoginUserDetails;
import com.example.domain.po.Permission;
import com.example.domain.po.RolePermission;
import com.example.domain.po.UserRole;
import com.example.mapper.PermissionMapper;
import com.example.mapper.RolePermissionMapper;
import com.example.mapper.UserRoleMapper;
import com.example.service.HomeService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class HomeServiceImpl implements HomeService {

    private final PermissionMapper permissionMapper;
    private final UserRoleMapper userRoleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public List<MenuTree> getMenuList() {

        // 从Spring Security上下文中获取当前用户ID
        LoginUserDetails userDetails = (LoginUserDetails) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        Integer userId = userDetails.getUser().getId();

        //获取所有的菜单
        // 获取用户所有菜单权限
        List<Permission> permissions = new ArrayList<>();
        //根据用户id获取当前账号所关联的的角色集合
        List<UserRole> userRoles = userRoleMapper.getUserRolesByUserId(userId);
        if (!CollectionUtils.isEmpty(userRoles)) {
            //获取用户角色id集合
            List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());

            //根据用户id查询用户关联的权限集合
            List<RolePermission> rolePermissions = rolePermissionMapper.getRolePermissionsByRoleIds(roleIds);
            if (!CollectionUtils.isEmpty(rolePermissions)) {
                //获取权限id
                List<Integer> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
                //根据权限id获取权限信息
                permissions = permissionMapper.batchGetPermissionsByPermissionId(permissionIds);
            }
        }

        // 构建菜单树
        return buildMenuTree(permissions);
    }
    private List<MenuTree> buildMenuTree(List<Permission> permissions) {
        // 创建菜单节点映射
        Map<Integer, MenuTree> menuMap = new HashMap<>();
        // 菜单节点映射
        for (Permission perm : permissions) {
            MenuTree menu = new MenuTree(perm);
            menuMap.put(perm.getId(), menu);

        }

        // 创建菜单树
        List<MenuTree> rootMenus = new ArrayList<>();

        // 构建树形结构
        for (Permission perm : permissions) {
                MenuTree menu = menuMap.get(perm.getId());
                if (menu.getParentId() == 0) {
                    rootMenus.add(menu);
                } else {
                    MenuTree parent = menuMap.get(perm.getParentId());
                    if (parent != null) {
                        parent.getChildren().add(menu);
                    }
            }
        }

        /*// 排序
        // 根节点排序 - 安全处理空值
        rootMenus.sort(Comparator.comparing(
                MenuTree::getOrderNo,
                Comparator.nullsLast(Comparator.naturalOrder())
        ));

        // 所有子节点排序 - 安全处理空值
        for (MenuTree node : menuMap.values()) {
            if (!node.getChildren().isEmpty()) {
                node.getChildren().sort(Comparator.comparing(
                        MenuTree::getOrderNo,
                        Comparator.nullsLast(Comparator.naturalOrder())
                ));
            }
        }*/

        return rootMenus;
    }
}
